import React, { useEffect, useMemo, useRef, useState } from 'react';

import { Button, Card, message, Popover, Skeleton, Steps } from 'antd';
import { size } from 'lodash';

import personalDataPic from '@/assets/entry/personalDataPic_0.png';
import IconFont from '@/components/IconFont';
import { defaultFormatResult, useRequest } from '@/hooks';
import { getFirstSimpleInfo, insertDevice, saveMaterials } from '@/pages/EntryManage/services';
import { RecruitContext } from '@/pages/RecruitEmail/Context';
import { toArray } from '@/utils/utils';

import xss from 'xss';
import TopBanner from '../components/TopBanner';
import { addFavorite, printScreenDown } from '../utils';
import { EntryDateModal, StepMaterials, StepNotice, StepUserInfo } from './components';
import styles from './index.less';

const { Step } = Steps;

/**
 * 新员工入职引导
 * /user/entryGuide
 */
const EntryGuide = ({ entryPersonnelCode }) => {
    const [currentStep, setCurrentStep] = useState();
    const [modalVisible, setModalVisible] = useState(false);
    const [changeEntryLoading, setChangeEntryLoading] = useState(false);
    const [uploadIng, setUploadIng] = useState();

    let context = React.useContext(RecruitContext);
    if (!context) {
        context = { data: null };
    }
    const { data, steps, current, handleChange } = context;
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    const customDot = (dot, { status, index }) => <div>{dot}</div>;

    const step1Ref = useRef();
    const step2Ref = useRef();
    const entryGuideWrapRef = useRef();
    const step2Info = localStorage.getItem('step2InfoData') ? JSON.parse(localStorage.getItem('step2InfoData')) : {};

    const handleScrollTop = () => {
        entryGuideWrapRef.current.scrollTo(0, 0);
    };

    // 获取入职人员信息
    const { loading, data: entryPersonnelData = {}, run: runGetFirstSimpleInfo } = useRequest(
        () => getFirstSimpleInfo({ entryPersonnelCode }),
        {
            ...defaultFormatResult
        }
    );

    useEffect(() => {
        if (entryPersonnelCode && entryPersonnelData) {
            setCurrentStep(entryPersonnelData?.step === 2 ? 2 : 0);
        }
    }, [entryPersonnelCode, entryPersonnelData]);

    // 第一步信息确认提交
    const { loading: step1Loading, run: runInsertDevice } = useRequest(param => insertDevice(param), {
        manual: true,
        onSuccess: ({ msg, code }) => {
            if (code === 10000) {
                message.success(msg);
                setCurrentStep(1);
                handleScrollTop();
            } else {
                message.error(msg);
            }
        }
    });

    // 第二步信息确认提交
    const { loading: step2Loading, run: runSaveMaterials } = useRequest(param => saveMaterials(param), {
        manual: true,
        onSuccess: ({ msg, code }) => {
            if (code === 10000) {
                message.success(msg);
                setCurrentStep(2);
                handleScrollTop();
                // 清除系统登录信息，防止登录信息冲突
                localStorage.removeItem('user');
                localStorage.removeItem('step2InfoData');
            } else {
                message.error(msg);
            }
        }
    });
    const step2Goback = () => {
        const { form } = step2Ref.current;
        localStorage.setItem('step2InfoData', JSON.stringify(form.getFieldsValue()));
    };
    // 根据步骤渲染
    const renderStep = useMemo(() => {
        switch (currentStep) {
            case 0:
                return <StepUserInfo wrappedComponentRef={step1Ref} entryPersonnelData={entryPersonnelData} />;
            case 1:
                return (
                    <StepMaterials
                        setUploadIng={setUploadIng}
                        wrappedComponentRef={step2Ref}
                        entryPersonnelData={{ ...entryPersonnelData, ...step2Info }}
                    />
                );
            case 2:
                return <StepNotice entryPersonnelData={entryPersonnelData} />;
            default:
                return null;
        }
    }, [currentStep, entryPersonnelData, step2Info]);

    const renderStepButton = useMemo(() => {
        switch (currentStep) {
            case 0:
                return (
                    <>
                        <Button
                            loading={step1Loading}
                            style={{ width: 200, height: 48 }}
                            type="primary"
                            onClick={() => {
                                const { form } = step1Ref.current;
                                if (form) {
                                    form.validateFieldsAndScroll((err, values) => {
                                        if (!err) {
                                            const param = {
                                                entryPersonnelCode,
                                                ...values,
                                                idPhoto: values?.idPhoto?.uploadResourceFile
                                                    ? [values?.idPhoto?.uploadResourceFile]
                                                    : []
                                            };
                                            runInsertDevice(param);
                                        }
                                    });
                                }
                            }}
                        >
                            下一步
                        </Button>
                    </>
                );
            case 1:
                return (
                    <>
                        <Button
                            type="ghost"
                            style={{ marginRight: 10, width: 200, height: 48, fontSize: 18 }}
                            onClick={() => {
                                step2Goback();
                                runGetFirstSimpleInfo();
                                setCurrentStep(0);
                            }}
                        >
                            上一步
                        </Button>

                        <Button
                            loading={step2Loading}
                            disabled={uploadIng}
                            type="primary"
                            style={{ marginLeft: 20, width: 200, height: 48, fontSize: 18 }}
                            onClick={() => {
                                const { form, materialsConfingData = {} } = step2Ref.current;
                                if (form) {
                                    form.validateFieldsAndScroll((err, values) => {
                                        if (!err) {
                                            const {
                                                electronMaterials = [],
                                                entityMaterials = []
                                            } = materialsConfingData;

                                            // 处理返回给后端的数据结构
                                            const materials = Object.entries(values).map(item => {
                                                // 分开是为了添加一个所属分组
                                                const electronArr = electronMaterials.filter(
                                                    subItem => subItem?.materialCode === item[0]
                                                );
                                                const entityArr = entityMaterials.filter(
                                                    subItem => subItem?.materialCode === item[0]
                                                );
                                                // 添加group区分分组！
                                                const materialDesc =
                                                    size(electronArr) > 0
                                                        ? { ...electronArr[0], group: 0 }
                                                        : { ...entityArr[0], group: 1 };
                                                return {
                                                    materialCode: item[0],
                                                    // 后端要求转字符串
                                                    materialValue:
                                                        typeof item[1] === 'object'
                                                            ? JSON.stringify(toArray(item[1]?.uploadResourceFile))
                                                            : item[1],
                                                    materialDesc
                                                };
                                            });
                                            const param = {
                                                entryPersonnelCode,
                                                materials
                                            };
                                            runSaveMaterials(param);
                                        }
                                    });
                                }
                            }}
                        >
                            提交
                        </Button>
                    </>
                );
            case 2:
                return (
                    <>
                        <Button
                            type="primary"
                            style={{ width: 200, height: 48, fontSize: 18 }}
                            onClick={() => {
                                printScreenDown(document.querySelector('#entryGuideWrap'), '入职须知', '', true);
                            }}
                        >
                            下载入职须知
                        </Button>
                        <Button
                            type="ghost"
                            style={{ marginLeft: 20, width: 200, height: 48, fontSize: 18 }}
                            onClick={() => {
                                addFavorite(window.location.href, '微微科技入职须知');
                            }}
                        >
                            收藏该网页
                        </Button>
                    </>
                );
            default:
                return null;
        }
    }, [
        currentStep,
        entryPersonnelCode,
        runGetFirstSimpleInfo,
        runInsertDevice,
        runSaveMaterials,
        step1Loading,
        step2Loading,
        uploadIng
    ]);

    return (
        <div ref={entryGuideWrapRef} className={styles.entryGuideWrap}>
            <TopBanner
                partLeft={{
                    render: (
                        <>
                            <p>
                                <b>
                                    {entryPersonnelData?.employeeName || entryPersonnelData?.employeeNameEn || '-'}
                                    ，你好！
                                </b>
                                请根据指引完成入职准备
                            </p>
                            <Steps
                                current={current}
                                onChange={handleChange}
                                progressDot={customDot}
                                className={styles.customStep}
                            >
                                {steps.map((item, index) => (
                                    <Step
                                        key={item.title}
                                        title=""
                                        description={item.title}
                                        status={item?.status}
                                        disabled={index >= data?.linkStep}
                                    />
                                ))}
                            </Steps>
                        </>
                    )
                }}
                partRight={{
                    render: <img src={personalDataPic} alt="" />
                }}
            />

            <div className={`${styles.guideCardWrap} ${styles.guideContWrap}`}>
                <Skeleton active loading={loading}>
                    <Card
                        bodyStyle={{
                            padding: '24px 0 0',
                            width: 860,
                            margin: '0 auto'
                        }}
                        id="entryGuideWrap"
                        bordered={false}
                    >
                        <div className={styles.cardHeader} data-hideinprint>
                            <span>新员工入职指引</span>
                            {entryPersonnelData?.entryStatus <= 5 && (
                                <span className={styles.rightText}>
                                    {!entryPersonnelData?.applyEntryDateStatus && (
                                        <>
                                            请您在 {entryPersonnelData.entryDate} 至公司入职
                                            <Button
                                                type="link"
                                                style={{ marginRight: 0 }}
                                                onClick={() => {
                                                    setModalVisible(true);
                                                }}
                                            >
                                                修改入职时间
                                            </Button>
                                        </>
                                    )}
                                    {entryPersonnelData?.applyEntryDateStatus === 'waitfor' && (
                                        <Popover
                                            content={
                                                <div className={styles.entryTimeTipContent}>
                                                    <div>
                                                        <span>原入职时间：</span>
                                                        {entryPersonnelData?.entryDate}
                                                    </div>
                                                    <div>
                                                        <span>期望入职时间：</span>
                                                        {entryPersonnelData?.applyEntryDate}
                                                    </div>
                                                    <div>
                                                        <span>修改原因：</span>
                                                        <div
                                                            style={{ wordBreak: 'break-all', display: 'inline' }}
                                                            // eslint-disable-next-line react/no-danger
                                                            dangerouslySetInnerHTML={{
                                                                __html: xss(
                                                                    entryPersonnelData?.applyEntryDateReason?.replace(
                                                                        /\s+/g,
                                                                        '<br>'
                                                                    )
                                                                )
                                                            }}
                                                        />
                                                    </div>
                                                </div>
                                            }
                                        >
                                            <IconFont icon="icontimeAdjusted" style={{ color: '#5590F6' }} />
                                            <span style={{ color: '#5590F6' }}>入职时间待定</span>
                                        </Popover>
                                    )}
                                    {entryPersonnelData?.applyEntryDateStatus === 'finished' &&
                                        `请您在 ${entryPersonnelData.entryDate} 至公司入职`}
                                </span>
                            )}
                        </div>
                        <Steps
                            data-hideinprint
                            id="entryGuideStepBar"
                            current={currentStep}
                            style={{ width: 580, marginBottom: 40 }}
                        >
                            <Step title="信息确认" />
                            <Step title="材料提供" />
                            <Step title="入职须知" />
                        </Steps>
                        {renderStep}
                    </Card>
                    <div className={styles.footerBtns}>{renderStepButton}</div>
                </Skeleton>
            </div>

            {/* 修改入职时间弹窗 */}
            <EntryDateModal
                oldEntryDate={entryPersonnelData?.entryDate}
                entryPersonnelCode={entryPersonnelData?.entryPersonnelCode}
                visible={modalVisible}
                setLoading={setChangeEntryLoading}
                confirmLoading={changeEntryLoading}
                title="修改入职时间"
                onCancel={() => {
                    setModalVisible(false);
                }}
                onOk={({ code, msg }) => {
                    if (code === 10000) {
                        runGetFirstSimpleInfo();
                        message.success('已收到您反馈的入职时间');
                        setModalVisible(false);
                    } else {
                        message.error(msg);
                    }
                }}
            />
        </div>
    );
};

export default EntryGuide;
